package com.example.base.datafilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class DataFilterAspect {

    @Around("@annotation(dataFilter)")
    public Object filterData(ProceedingJoinPoint joinPoint, DataFilter dataFilter) throws Throwable {
        Object result = joinPoint.proceed(); // 调用被注解的方法

        // 获取需要过滤的字段
        String[] filterFields = dataFilter.value();

        if (result instanceof List) {
            // 对数据列表中的对象进行字段过滤处理
            List dataList = (List) result;
            for (int i = 0; i < dataList.size() ; i++) {
                Object obj=dataList.get(i);
                SimplePropertyPreFilter filter = new SimplePropertyPreFilter(obj.getClass(), filterFields);
                String jsonString = JSON.toJSONString(obj, filter);
                obj=JSON.parse(jsonString);
                dataList.set(i,obj);
            }
        }else if(result instanceof IPage) {
            Page page=(Page) result;
            List list=page.getRecords();
            for (int i = 0; i < list.size() ; i++) {
                Object obj=list.get(i);
                SimplePropertyPreFilter filter = new SimplePropertyPreFilter(obj.getClass(), filterFields);
                String jsonString = JSON.toJSONString(obj, filter);
                obj=JSON.parse(jsonString);
                list.set(i,obj);
            }
        }else {
            // 单个数据对象的字段过滤处理
            SimplePropertyPreFilter filter = new SimplePropertyPreFilter(result.getClass(), filterFields);
            String jsonString = JSON.toJSONString(result, filter);
            // 处理过滤后的JSON数据
            result=JSON.parse(jsonString);
        }
        return result;
    }
}
